package com.abcdefg.demo.topic;

import com.abcdefg.demo.constants.Constants;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class TopicProducer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.建立连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.Host);
        factory.setPort(Constants.Port);
        factory.setVirtualHost(Constants.VirtualHost);
        factory.setUsername(Constants.UserName);
        factory.setPassword(Constants.Password);
        Connection connection = factory.newConnection();
        //2.创建信道
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(Constants.TOPIC_EXCHANGE, BuiltinExchangeType.TOPIC, true);
        channel.queueDeclare(Constants.TOPIC_QUEUE1, true, false, false, null);
        channel.queueDeclare(Constants.TOPIC_QUEUE2, true, false, false, null);

        channel.queueBind(Constants.TOPIC_QUEUE1,Constants.TOPIC_EXCHANGE,"*.a.*");
        channel.queueBind(Constants.TOPIC_QUEUE2,Constants.TOPIC_EXCHANGE,"*.*.b");
        channel.queueBind(Constants.TOPIC_QUEUE2,Constants.TOPIC_EXCHANGE,"c.#");


        String msg_a="hello topic! i'm af.a.f...";
        channel.basicPublish(Constants.TOPIC_EXCHANGE,"af.a.f",null,msg_a.getBytes());
        String msg_b="hello topic! i'm af.a.b...";
        channel.basicPublish(Constants.TOPIC_EXCHANGE,"af.a.b",null,msg_b.getBytes());
        String msg_c="hello topic! i'm c.asdf...";
        channel.basicPublish(Constants.TOPIC_EXCHANGE,"c.asdf",null,msg_c.getBytes());

        //释放资源
        connection.close();
    }
}
